﻿using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

namespace UniFramework.Skill
{
	public partial class Skill
	{
		private Dictionary<int, SkillEffectLogic> _skillEffectLogicDic = new();

		private void OnLogicFrameUpdateEffect()
		{
			var dataList = skillConfig.skillEffectList;
			if (dataList == null || dataList.Count == 0) return;
			foreach (var data in dataList)
			{
				int hashCode = data.GetHashCode();
				if (data.effectPrefab != null && _curLogicFrame == data.triggerFrame)
				{
					GameObject effectObj = GameObject.Instantiate(data.effectPrefab);
					effectObj.transform.localPosition = Vector3.zero;
					effectObj.transform.localRotation = Quaternion.identity;
					effectObj.transform.localScale = Vector3.one;
					SkillEffectRender effectRender = effectObj.GetOrAddComponent<SkillEffectRender>();
					SkillEffectLogic skillEffectLogic = new SkillEffectLogic(this, this.releaser, effectRender, data);
					effectRender.SetLogicObjectAndInitData(skillEffectLogic);
					_skillEffectLogicDic.TryAdd(hashCode, skillEffectLogic);
				}

				if (_curLogicFrame == data.endFrame)
				{
					TryDestroyEffect(hashCode);
				}

				if (_skillEffectLogicDic.TryGetValue(hashCode, out var logic))
				{
					logic.OnLogicFrameUpdate(_curLogicFrame);
				}
			}
		}


		/// <summary>
		///  销毁特效预制体
		/// </summary>
		/// <param name="hashCode"></param>
		private void TryDestroyEffect(int hashCode)
		{
			if (_skillEffectLogicDic.TryGetValue(hashCode, out var logic))
			{
				logic.OnDie();
				_skillEffectLogicDic.Remove(hashCode);
			}
		}
	}
}